package com.codemonkey.lq.extend.excelverification;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public final class CellContext {

	private String cellName;
	// 从1开始
	private int cellIndex;
	private Object cellVal;
	private Map<String, Object> rowContext;

	public CellContext(int cellIndex, String cellName, Object cellVal,
			Map<String, Object> rowContext) {
		this.cellIndex = cellIndex;
		this.cellName = cellName;
		this.cellVal = cellVal;
		this.rowContext = rowContext;
	}

	public void setCellIndex(int cellIndex) {
		this.cellIndex = cellIndex;
	}

	public void setCellName(String cellName) {
		this.cellName = cellName;
	}

	public void setCellVal(Object cellVal) {
		this.cellVal = cellVal;
	}

	public int getCellIndex() {
		return cellIndex;
	}

	public String getCellName() {
		return cellName;
	}

	public Object getCellVal() {
		return cellVal;
	}

	public Map<String, Object> getRowContext() {
		return rowContext;
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder("###");
		sb.append(this.getClass().getSimpleName()).append(" :");
		sb.append(" cellName = [ ").append(this.cellName).append(" ]").append(
				System.lineSeparator());
		sb.append(" cellIndex = [ ").append(this.cellIndex).append(" ]").append(
				System.lineSeparator());
		sb.append(" cellVal = [ ").append(this.cellVal).append(" ]").append(System.lineSeparator());
		sb.append(" rowContext = [ ").append(this.rowContext).append(" ]").append(
				System.lineSeparator());
		return sb.toString();
	}

	// /////////////////////////////fail deal ///////////////////////////////////////

	private List<Throwable> exceptionList = new ArrayList<Throwable>();
	private List<String> errorMsgList = new ArrayList<String>();

	// ------------------------------------------------   set

	/**
	 * 方法执行失败时, 设置失败原因
	 * @param errorMsg
	 */
	public void addErrorMsg(String errorMsg) {
		errorMsgList.add(errorMsg);
	}

	/**
	 * 方法执行失败时, 设置产生失败的异常原因
	 * @param exception
	 */
	public void addException(Throwable exception) {
		exceptionList.add(exception);
	}

	// ------------------------------------------------   get	
	/**
	 * 如果方法执行失败, 由这个方法返回失败的原因
	* @return
	*/
	public String getFailMsg() {
		StringBuilder sb = new StringBuilder("");

		if (!exceptionList.isEmpty()) {
			for (Throwable exception : exceptionList) {
				sb.append(getRootCause(exception).toString());
				sb.append(System.lineSeparator());
			}
		}

		if (!errorMsgList.isEmpty()) {
			for (String errorMsg : errorMsgList) {
				sb.append(errorMsg);
				sb.append(System.lineSeparator());
			}
		}

		return sb.toString();
	}

	private Throwable getRootCause(Throwable throwable) {
		Throwable cause;
		while ((cause = throwable.getCause()) != null) {
			throwable = cause;
		}
		return throwable;
	}
}
